package cz.kfad.ofrss.common;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
import cz.kfad.ofrss.R;
import cz.kfad.ofrss.activity.ChannelActivity;
import cz.kfad.ofrss.activity.ChannelsActivity;
import cz.kfad.ofrss.backend.BackendService;
import cz.kfad.ofrss.backend.IBackend;
import cz.kfad.ofrss.model.Channel;
import cz.kfad.ofrss.rss.ContentFetcherImp;

public class AsynChannel extends AsyncTask<Channel, Void, Void> {

	private Activity context;

	@Override
	protected void onPreExecute() {
		Toast.makeText(context, context.getString(R.string.channelWillBeProcessed), Toast.LENGTH_SHORT).show();
	}

	@Override
	protected Void doInBackground(Channel... params) {
		if (!NetworkHelper.isNetworkConnected(context)) {
			return null;
		}
		Channel channel = params[0];
		IBackend backend = BackendService.createBackend(context);
		backend.fetchChannel(channel);
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		if (context == null) {
			return;
		}
		if (context instanceof ChannelsActivity) {
			((ChannelsActivity) context).reload();
		} else if (context instanceof ChannelActivity) {
			((ChannelActivity) context).reload();
		}
		if (!NetworkHelper.isNetworkConnected(context)) {
			return;
		}
		AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				new ContentFetcherImp(context).fetchContentForAll();
				return null;
			}

		};
		asyncTask.execute();
	}

	public void setContext(Activity context) {
		this.context = context;
	}


}
